package com.ebeitech.land.auction.wxapi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.ebeitech.auction.http.EbeiErrorCode;
import com.ebeitech.auction.http.HttpService;
import com.ebeitech.auction.http.model.LoginWeiXinModel;
import com.ebeitech.auction.http.service.HttpAuctionServiceRx;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.ViewUtil;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * Created by alice on 2017/11/15.
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

	private Context mContext;
	private IWXAPI api;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		api = WeiXinUtil.getInstance().getIWXAPI();
		try {
			api.handleIntent(getIntent(), this);
		} catch (Exception e) {

		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		api.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq baseReq) {

	}

	@Override
	public void onResp(BaseResp resp) {
		int errorCode = resp.errCode;
		switch (errorCode) {
			case BaseResp.ErrCode.ERR_OK:
				//用户同意
				String code = ((SendAuth.Resp) resp).code;
				// 向服务器请求
				doLoginWithServer(code);
				return;
			case BaseResp.ErrCode.ERR_AUTH_DENIED:
				//用户拒绝
				break;
			case BaseResp.ErrCode.ERR_USER_CANCEL:
				//用户取消
				break;
			default:
				break;
		}
		if (!StringUtil.isEmpty(resp.errStr)) {
			ViewUtil.toastMsg(this, resp.errStr);
		}
		finish();
	}

	/**
	 * 向后台请求登陆
	 */
	private void doLoginWithServer(String code) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("code", code);

		HttpService mHttpService = HttpService.getInstance();
		HttpAuctionServiceRx mHttpAuctionServiceRx = mHttpService.getRxGsonRetrofit().create(HttpAuctionServiceRx.class);
		final Call<ResponseBody> call = mHttpAuctionServiceRx.getWechatLogin(params);
		mHttpService.executeHttp(mContext, call, new HttpService.HttpListener<LoginWeiXinModel>() {
			@Override
			public void onStart() {

			}

			@Override
			public void onError(EbeiErrorCode errorCode) {

			}

			@Override
			public void onSuccess(LoginWeiXinModel result) {
				// 看后台该微信号是否绑定用户
				// 如果没绑定就去登陆页面绑定
				// 如果绑定好了,直接解析数据
				Intent intent = new Intent(WeiXinUtil.ACTION_WEIXIN_LOGIN);
				intent.putExtra("loginWeiXinModel", result);
				sendBroadcast(intent);
				finish();
			}
		}, LoginWeiXinModel.class);
	}

}
